/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}

	/**
	 * todo 执行bean工厂的后置处理器，但是，处理的是两种处理器 BFPP 和 BDRPP（其中BDRPP是BFPP的子集）
	 *
	 * @param beanFactory               bean工厂（bean其实是DefaultListableBeanFactory）
	 * @param beanFactoryPostProcessors todo 自定义的bean工厂后置处理器，默认是个空的List（不是spring自己内部的BFPP
	 * 			                               是通过context.addBeanFactoryPostProcessor(beanFactoryPostProcessor)添加的）
	 *                                  <p>
	 *                                  beanFactoryPostProcessors是通过getBeanFactoryPostProcessors()方法获取的
	 *                                  getBeanFactoryPostProcessors()是通过this.beanFactoryPostProcessors集合属性中获取的
	 *                                  <p>
	 *                                  <p>
	 *                                  * 	1.先查看入参beanFactoryPostProcessors中的
	 *                                  * 	2.查看所有已注册bean定义的BeanDefinitionRegistryPostProcessor
	 *                                  * 		2.1.实现PriorityOrdered接口的  排序后按顺序执行postProcessBeanDefinitionRegistry方法
	 *                                  * 		2.2.实现Ordered接口并且还未执行的  排序后按顺序执行postProcessBeanDefinitionRegistry方法
	 *                                  * 		2.3.剩余的BeanDefinitionRegistryPostProcessor 执行其postProcessBeanDefinitionRegistry方法
	 *                                  * 	3.按上面执行循序调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法
	 *                                  * 	4.调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法
	 *                                  *
	 *                                  * 	重复调用BeanDefinitionRegistryPostProcessor的步骤，处理BeanFactoryPostProcessor
	 *                                  *
	 *                                  * 优先级：
	 *                                  * 	1：BeanDefinitionRegistryPostProcessor  >  BeanFactoryPostProcessor
	 *                                  * 	2：入参beanFactoryPostProcessors > 实现PriorityOrdered接口  > 实现Ordered接口 > 其他
	 *                                  <p>
	 *                                  ————————————————
	 *                                  版权声明：本文为CSDN博主「豆北儿」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
	 *                                  原文链接：https://blog.csdn.net/luo_mu_hpu/article/details/107337443
	 */
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// WARNING: Although it may appear that the body of this method can be easily
		// refactored to avoid the use of multiple loops and multiple lists, the use
		// of multiple lists and multiple passes over the names of processors is
		// intentional. We must ensure that we honor the contracts for PriorityOrdered
		// and Ordered processors. Specifically, we must NOT cause processors to be
		// instantiated (via getBean() invocations) or registered in the ApplicationContext
		// in the wrong order.
		//
		// Before submitting a pull request (PR) to change this method, please review the
		// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
		// to ensure that your proposal does not result in a breaking change:
		// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		// todo 无论如何，优先执行BeanDefinitionRegistryPostProcessors
		//  将已经执行过的BFPP存放到processedBeans的set集合中，避免重复执行（set可以去重，具有唯一性）
		Set<String> processedBeans = new HashSet<>();

		// todo 1.判断beanFactory是否是BeanDefinitionRegistry类型，此处是DefaultListableBeanFactory实现了BeanDefinitionRegistry接口，所以为true
		if (beanFactory instanceof BeanDefinitionRegistry) {
			// todo 强制类型转换
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

			/**
			 * 常规的后置处理器（常规的后置处理器就是BeanFactoryPostProcessor类型的），用来存放BeanFactoryPostProcessor的集合
			 */
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			/**
			 * 注册处理器，用来存放BeanDefinitionRegistryPostProcessor类型的的后置处理器
			 */
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			/**
			 *  todo 先处理的是外部的后置处理器（自定义的后置处理器）
			 *     beanFactoryPostProcessors默认为空，跳过循环
			 *      除非通过context.addBeanFactoryPostProcessor(beanFactoryPostProcessor)添加
			 * 	 2.首先处理入参中的beanFactoryPostProcessors
			 * 	    // 遍历所有的beanFactoryPostProcessors, 将BeanDefinitionRegistryPostProcessor和普通BeanFactoryPostProcessor区分开
			 */
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				// todo 针对外部的BFPP，根据类型的不同，添加到不同类型的list集合中
				// todo 2.1 如果是BeanDefinitionRegistryPostProcessor
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					// todo 2.1.1 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					// todo 添加BDRPP
					registryProcessors.add(registryProcessor);
				} else {
					// todo 2.2 否则，只是普通的BeanFactoryPostProcessor
					// todo 2.2.1 添加到regularPostProcessors(用于最后执行postProcessBeanFactory方法)
					regularPostProcessors.add(postProcessor);
				}
			}


			// ======================上面处理的是外部BFPP（addBeanFactoryPostProcessor()添加的）=============================

			/**
			 * 	todo ================================================================================
			 * 		1、 将外部的后置处理器分别存到registryProcessor集合和regularPostProcessors集合中
			 * 		2、 BDRPP在添加到registryProcessor之前调用了postProcessBeanDefinitionRegistry()方法
			 * 			BFPP添加到regularPostProcessors集合中，在后面统一处理
			 * 	todo ================================================================================
			 */
			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			/**
			 * todo currentRegistryProcessors用于保存内部准备执行的BeanDefinitionRegistryPostProcessor类型的集合
			 */
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			/**
			 * todo 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
			 *   3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
			 */
			String[] postProcessorNames =     // todo 内部的BDRPP
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			/**
			 * 为什么要在最开始注册这个BFPP的bean？？？
			 * 因为spring工厂需要去解析xml、或者扫描注解来完成bean定义的加载
			 * 而这些功能都是需要在spring工厂初始化完成之前去执行
			 * 要么在工厂最开始的时候、要么在工程初始化之中，反正不能在初始化之后
			 *
			 * eg：使用注解的方式加载Bean定义
			 * spring在一开始的时候就注册了一个BDRPP实现了BeanFactoryPostProcessor接口，用来插手springFactory的实例化过程
			 * 此处断点可知这个BDRPP叫做：ConfigurationAnnotationProcessor （spring内部的bean工厂后置处理器）
			 */
			// todo 3.2 遍历处理符合条件的postProcessorNames
			for (String ppName : postProcessorNames) {
				// todo 3.3 检测是否实现了PriorityOrdered接口的BDRPP
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					// todo 3.4 根据ppName获取bean，并添加到内部需要执行的BeanDefinitionRegistryPostProcessor的集合
					// todo >>>>>> 这边通过beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class))，会实例化对应的对象
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// todo 3.5 将要被执行的BFPP添加到processedBeans（set集合）中，避免重复执行
					processedBeans.add(ppName);
				}
			}

			// todo 3.6 将内部需要执行的BFPP进行排序（因为currentRegistryProcessors集合中的BDRPP可能有多个，需要进行排序，来保证执行的顺序）
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			
			registryProcessors.addAll(currentRegistryProcessors);

			/**
			 * todo 3.8 这个方法最重要，最终执行BDRPP的操作
			 * 开始循环调用BeanDefinitionRegistryPostProcessor
			 *
			 * todo 如果是使用注解的方式加载bean定义
			 * 那么spring内部存在一个ConfigurationClassPostProcessor（实现了的BeanDefinitionRegistryPostProcessors）
			 * 用来处理@Configuration/@Component等注解，扫描、注册包下的类
			 * 处理@Import/@ImportResource/@Bean等...
			 */
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			// todo 3.9 执行完成之后，清空待执行的内部BDRPP集合
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// todo 4.调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类（过程跟上面的步骤3基本一样）
			//   4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor
			//           可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// todo 检测是否实现了Ordered接口，并且在processedBeans（set集合）中不存在的BDRPP
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			// todo 4.2 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// todo 5 最后，调用所有剩下的BeanDefinitionRegistryPostProcessors（包含外部BDRPP 和 内部的BDRPP）
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				// todo 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					// todo 在processedBeans（set集合）中不存在的BDRPP(也就是没有实现排序接口的BDRPP)
					//     5.2 跳过已经执行过的
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						// todo 5.3 reiterate=true，如果有BFPP执行，可能还有其他BFPP需要执行，需要再次进入while循环
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				// 5.4 todo 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			// todo 外部bean工厂后置处理器，方法的回调在这边统一执行
			// todo 6. 所有外部实现了BDRPP接口的后置处理器方法的回调（执行beanFactoryPostProcessors()方法）
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			// todo 7. 所有外部实现了BFPP接口的后置处理器方法的回调（执行beanFactoryPostProcessors()方法）
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		} else {
			// Invoke factory processors registered with the context instance.
			// todo 不是BeanDefinitionRegistry类型，不需要对外部后置处理器进行类型划分成BDRPP和BFPP
			// todo 直接执行BFPP实现类方法的回调
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// todo 8.找出所有实现BeanFactoryPostProcessor接口的类
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// // todo 将所有的BeanFactoryPostProcessor类型的BFPP，按照priorityOrdered、ordered和不排序进行分割，封装成list集合
		// todo 实现了priorityOrdered类型的BFPP
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// todo 实现了ordered类型的BFPP
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// todo 未实现排序接口的BFPP
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();

		// todo 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开
		for (String ppName : postProcessorNames) {

			// todo 8.2 跳过已经执行过的
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// todo 8.3 添加实现了PriorityOrdered接口的BeanFactoryPostProcessor
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				// todo 8.4 添加实现了Ordered接口的BeanFactoryPostProcessor的beanName
				orderedPostProcessorNames.add(ppName);
			} else {
				// todo 8.5 添加剩下的普通BeanFactoryPostProcessor的beanName
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		// todo 9.调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor
		// todo 9.1 将priorityOrderedPostProcessors集合进行排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		// todo 9.2 BFPP接口实现类方法的回调
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		// todo 10.调用所有实现Ordered接口的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			// todo 10.1 获取postProcessorName对应的bean实例, 添加到orderedPostProcessors, 准备执行
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		// todo 10.2 对orderedPostProcessors排序
		sortPostProcessors(orderedPostProcessors, beanFactory);
		// todo 10.3 遍历orderedPostProcessors, 执行postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		// todo 11.调用所有剩下的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			// todo 11.1 获取postProcessorName对应的bean实例, 添加到nonOrderedPostProcessors, 准备执行
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		// todo 11.2 遍历nonOrderedPostProcessors, 执行postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		// todo 12.清除元数据缓存（mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType），
		//	       因为后处理器可能已经修改了原始元数据，例如， 替换值中的占位符...
		beanFactory.clearMetadataCache();
	}

	/**
	 * todo 注册BeanPostProcessors ==》将所有的BPP接口的实现类，添加到ConfigurationListAbleBeanFactory类中的beanPostProcessors集合属性中
	 *
	 * todo 注册的顺序：PriorityOrderedBPP(实现了PriorityOrdered接口的BPP) ---> OrderedBPP（实现了Ordered接口的BPP）
	 *                      ---> regularBPP（普通的BPP） ---> internalBPP（spring内部的BPP）
	 *
	 *
	 * @param beanFactory          ConfigurableListableBeanFactory
	 * @param applicationContext   AbstractApplicationContext
	 */
	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		// WARNING: Although it may appear that the body of this method can be easily
		// refactored to avoid the use of multiple loops and multiple lists, the use
		// of multiple lists and multiple passes over the names of processors is
		// intentional. We must ensure that we honor the contracts for PriorityOrdered
		// and Ordered processors. Specifically, we must NOT cause processors to be
		// instantiated (via getBean() invocations) or registered in the ApplicationContext
		// in the wrong order.
		//
		// Before submitting a pull request (PR) to change this method, please review the
		// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
		// to ensure that your proposal does not result in a breaking change:
		// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

		// todo 获取指定类型的BPP名称，返回数组
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		// todo 上面计算beanProcessorTargetCount的时候，有一个 “+1”操作，预留一个位置，添加了BeanPostProcessorChecker
		// todo BeanPostProcessorChecker BPP的检查类，没有实际功能，只输出了log日志
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// todo 将BPP进行归类
		// todo 1、实现了PriorityOrdered接口的
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// todo 2、spring内部的
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		// todo 3、实现了Ordered接口的
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// todo 4、普通BPP，没有实现任何接口的
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();

		// todo 遍历postProcessorNames（BPP的名称），归类
		for (String ppName : postProcessorNames) {
			// todo 匹配是否是实现了PriorityOrdered接口的BPP
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				// todo 判断BPP的类型是否是MergedBeanDefinitionPostProcessor，是就添加到spring内部的BPP集合中
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
				// todo 匹配是否是实现了Ordered接口的BPP
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			} else {
				// todo 常规的BPP，没有实现任何排序接口，也不是spring内部bean
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		// todo 首先，注册实现了PriorityOrdered接口的BPP
		// todo 排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		// todo 注册BPP（beanFactory.addBeanPostProcessor(postProcessor)）
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		// todo 下一步，注册实现了Ordered接口的BPP
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			// todo 如果BPP是MergedBeanDefinitionPostProcessor类型，添加到internalPostProcessors集合中
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		// todo 现在，注册所有常规的（普通的）BPP
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			// todo 如果BPP是MergedBeanDefinitionPostProcessor类型，添加到internalPostProcessors集合中
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				// todo 添加到内部的BPP集合中
				internalPostProcessors.add(pp);
			}
		}
		// todo 不需要排序
		// todo 注册BPP（beanFactory.addBeanPostProcessor(postProcessor)）
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		// todo 最后，再注册所有内部的BPP
		// todo 拍寻
		sortPostProcessors(internalPostProcessors, beanFactory);
		// 注册BPP（beanFactory.addBeanPostProcessor(postProcessor)）
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
					.tag("postProcessor", postProcessor::toString);

			// todo 这里就是真正执行BDRPP的地方！！！
			postProcessor.postProcessBeanDefinitionRegistry(registry);
			postProcessBeanDefRegistry.end();
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
					.tag("postProcessor", postProcessor::toString);
			postProcessor.postProcessBeanFactory(beanFactory);
			postProcessBeanFactory.end();
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		if (beanFactory instanceof AbstractBeanFactory) {
			// Bulk addition is more efficient against our CopyOnWriteArrayList there
			((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
		} else {
			for (BeanPostProcessor postProcessor : postProcessors) {
				beanFactory.addBeanPostProcessor(postProcessor);
			}
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
